package br.com.spread.svnutils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class Redmine {
    /**
	 * 
	 */
    public static void main(String[] args) {
        DAVRepositoryFactory.setup();

        String url = "http://10.55.1.7:8080/svn/siaad";
        String name = "jose.nascimento";
        String password = "c4ss1n1";

        SVNRepository repository = null;

        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
            ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
            repository.setAuthenticationManager(authManager);

            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -7);

            long endRevision = repository.getDatedRevision(c.getTime());
            long startRevision = -1; // HEAD (the latest) revision

            final Collection<SVNLogEntry> logEntries = new LinkedList<SVNLogEntry>();
            repository.log(new String[] { "" }, startRevision, endRevision, true, false, new ISVNLogEntryHandler() {
                public void handleLogEntry(SVNLogEntry logEntry) {
                    logEntries.add(logEntry);
                }
            });

            // Map<String, Contents> t = new LinkedHashMap<String, Contents>();

            for (Iterator<?> entries = logEntries.iterator(); entries.hasNext();) {
                SVNLogEntry logEntry = (SVNLogEntry) entries.next();

                Contents contents = new Contents(logEntry);

                if (isForDelivery(logEntry)) {

                    // if (t.get(logEntry.getMessage()) == null) {
                    // Contents contents = new Contents(logEntry);
                    // t.put(contents.getMessage(), contents);
                    // }

                    if (logEntry.getChangedPaths().size() > 0) {
                        Set<?> changedPathsSet = logEntry.getChangedPaths().keySet();

                        for (Iterator<?> changedPaths = changedPathsSet.iterator(); changedPaths.hasNext();) {
                            SVNLogEntryPath entry = (SVNLogEntryPath) logEntry.getChangedPaths().get(
                                    changedPaths.next());
                            if (SVNNodeKind.FILE.equals(entry.getKind())) {
                                contents.addFile(entry.getType(),
                                        entry.getPath().replaceAll("/branches/[_A-Z0-9]*/03-Implementacao/", ""));
                            }
                        }
                    }
                }

                System.out.println(contents);
            }

            // for (Contents c1 : t.values()) {
            // System.out.println(c1);
            // }

        } catch (SVNException e) {
            e.printStackTrace();
        }
    }

    private static boolean isForDelivery(SVNLogEntry logEntry) {
        if (logEntry.getMessage().indexOf("RTC 000000") == -1) {
            return logEntry.getMessage().startsWith("RTC") || logEntry.getMessage().startsWith("BR")
                    || logEntry.getMessage().startsWith("BRN");
        }
        return false;
    }
}

class Contents {
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    private Map<Character, List<String>> files = new HashMap<Character, List<String>>();

    private SVNLogEntry logEntry;

    public Contents(SVNLogEntry logEntry) {
        this.logEntry = logEntry;
    }

    public void addFile(char type, String file) {
        if (files.get(type) == null) {
            files.put(type, new ArrayList<String>());
        }
        if (!files.get(type).contains(file)) {
            files.get(type).add(file);
        }
    }

    public List<String> getListFiles(char type) {
        return files.get(type);
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return logEntry.getMessage();
    }

    /**
     * @return the message
     */
    public String getDateAsString() {
        return sdf.format(logEntry.getDate());
    }

    public String getBrnNumber(String message) {
        String result = "NAO INFORMADO";

        Map<String, String> demandas = new HashMap<String, String>();

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/demandas.txt")));
            String line;

            while ((line = br.readLine()) != null) {
                demandas.put(line.split(";")[0], line.split(";")[1]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Pattern p = Pattern.compile("^RTC [0-9]*");
        Matcher m = p.matcher(message);
        if (m.find()) {
            String key = message.substring(m.start(), m.end());
            result = demandas.get(key);
        }

        return result;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();

        if (getMessage().startsWith("BR")) {
            sb.append(String.format("SIAAD - %s\n\n", getMessage()));
        } else if (getMessage().startsWith("RTC")) {
            sb.append(String.format("SIAAD - %s - %s\n\n", getBrnNumber(getMessage()), getMessage()));
        }

        sb.append("Entrega de código-fonte e aplicativo\n");
        sb.append(String.format("Data da alteração: %s\n", sdf.format(logEntry.getDate())));
        sb.append("Raiz do SVN: http://10.55.1.7:8080/svn/siaad/trunk/MDS_Unificada/TE177/03-Implementacao/\n\n");

        List<String> alterados = new ArrayList<String>();

        if (getListFiles('M') != null) {
            for (String file : getListFiles('M')) {
                alterados.add(file);
            }
        }

        if (getListFiles('A') != null) {
            for (String file : getListFiles('A')) {
                alterados.add(file);
            }
        }

        if (getListFiles('R') != null) {
            for (String file : getListFiles('R')) {
                alterados.add(file);
            }
        }

        if (!alterados.isEmpty()) {
            sb.append("-------------------------------------------\n");
            sb.append("Arquivos a serem copiados\n");
            sb.append("-------------------------------------------\n");
            Collections.sort(alterados);

            for (String file : alterados) {
                sb.append(file + "\n");
            }
        }

        List<String> removidos = new ArrayList<String>();

        if (getListFiles('D') != null) {
            for (String file : getListFiles('D')) {
                removidos.add(file);
            }
        }

        if (!removidos.isEmpty()) {
            sb.append("\n\n");
            sb.append("-------------------------------------------\n");
            sb.append("Arquivos a serem removidos (se existirem)\n");
            sb.append("-------------------------------------------\n");

            for (String file : removidos) {
                sb.append(file + "\n");
            }
        }

        sb.append("\n");
        sb.append("-------------------------------------------\n");
        sb.append("Pacote para Deployment\n");
        sb.append("-------------------------------------------\n");
        sb.append("Build/siaad.ear\n");
        sb.append("Build/siaad.ear.MD5");

        sb.append("\n\n\n");

        return sb.toString();
    }
}
